<template>
  <div class="login">
    <el-row justify="center" align="middle" style="height: 100vh;">
      <el-col :span="4" :xs="18" :sm="12" :md="8" :lg="6" :xl="4"> <!-- 进一步减小宽度 -->
        <el-card shadow="always" class="login-card">
          <el-form :model="formData" :rules="rules" size="small" label-position="top" ref="loginForm"> <!-- 使用 small 尺寸 -->
            <el-form-item label="用户名:" prop="username">
              <el-input v-model="formData.username" type="text" placeholder="请输入用户名" clearable>
                <template #prepend>
                  <el-button :icon="UserFilled"></el-button>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="密码:" prop="pwd">
              <el-input v-model="formData.pwd" type="password" placeholder="请输入密码" show-password clearable>
                <template #prepend>
                  <el-button :icon="Lock"></el-button>
                </template>
              </el-input>
            </el-form-item>
            <el-row :gutter="8"> <!-- 减小按钮间距 -->
              <el-col :span="12">
                <el-form-item>
                  <el-button type="success" @click="submitForm" class="full-width">登录</el-button>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item>
                  <el-button type="primary" @click="resetForm" class="full-width">重置</el-button>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="8"> <!-- 减小按钮间距 -->
              <el-col :span="12">
                <el-form-item>
                  <el-button type="plain" @click="goToRegister" class="full-width">注册账户</el-button>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item>
                  <el-button type="plain" @click="forgotPassword" class="full-width">忘记密码</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import { UserFilled, Lock } from "@element-plus/icons-vue";
import { loginApi } from '@/api/userApi'; // 假设你的登录 API
import { useUserStore } from '@/store/useUserStore';
import { useRouter } from "vue-router";
import CryptoJS from "crypto-js"; // 导入 crypto-js

// Reactive form data
const formData = reactive({
  username: '',
  pwd: ''
});

// Form validation rules
const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  pwd: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
});

// Reference to form
const loginForm = ref();
const userStore = useUserStore();
const router = useRouter();

// 提交表单
async function submitForm() {
  try {
    await loginForm.value.validate();

    // 加密密码
    const secretKey = "AAAABBBBCCCCDDDD"; // 密钥
    const encryptedPwd = CryptoJS.AES.encrypt(formData.pwd, CryptoJS.enc.Utf8.parse(secretKey), {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7
    }).toString();

    // 创建带加密密码的登录请求数据
    const loginData = {
      username: formData.username,
      pwd: encryptedPwd // 使用加密后的密码进行登录
    };

    // 发送加密密码的登录请求
    const result = await loginApi(loginData);

    // 获取并存储后端返回的用户信息
    handleLoginSuccess(result.data);

  } catch (error) {
    console.error('Login failed:', error);
    // 可以在这里显示友好的错误提示
    alert('登录失败，请检查用户名和密码。'); // 你可以替换为一个合适的通知组件
  }
}

// 处理登录成功的逻辑
function handleLoginSuccess(data) {
  let token = data.token;
  let backAuthorizedUris = data.backAuthorizedUris;
  let userRoutes = data.userRoutes;
  let userInfo = extractUserInfoFromToken(token);

  // 设置用户的信息
  userInfo.backAuthorizedUris = backAuthorizedUris;
  userInfo.userRoutes = userRoutes;

  // 调用 store 进行存储
  userStore.storeUserInfo(userInfo);
  userStore.storeToken(token);
  console.log(userStore.token);

  // 跳转到首页
  router.replace("/");
}

// 解析 token 获取用户信息
function extractUserInfoFromToken(token) {
  let payload = atob(token.split(".")[1]);
  let payloadObj = JSON.parse(payload);
  return JSON.parse(payloadObj["TokenDTO"]);
}

// 重置表单
function resetForm() {
  loginForm.value.resetFields();
}

// 跳转到注册页面
function goToRegister() {
  router.replace('/register');
}

// 跳转到忘记密码页面
function forgotPassword() {
  router.replace('/forgotPassword');
}
</script>

<style scoped>
.login {
  background-color: #EFF3F5;
}

.login-card {
  padding: 12px; /* 进一步减少内边距 */
  border-radius: 8px;
  background-color: #F6F7F9; /* 半透明背景 */
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

:deep(.el-form-item__label) {
  color: #000000 !important; /* 确保文本颜色适合新的背景 */
}

.full-width {
  width: 100%;
}

.el-row + .el-row {
  margin-top: 8px; /* 进一步减少行之间的间距 */
}

/* Optional: Customize the input and button styles for a more consistent look */
:deep(.el-input__inner) {
  height: 32px; /* 减小输入框高度 */
  font-size: 12px;
}

:deep(.el-button) {
  height: 32px; /* 减小按钮高度 */
  font-size: 12px;
}

:deep(.el-button--success) {
  background-color: #67c23a;
  border-color: #67c23a;
}

:deep(.el-button--primary) {
  background-color: #409eff;
  border-color: #409eff;
}

:deep(.el-button--plain) {
  color: #606266;
  background: #fff;
  border-color: #dcdfe6;
}
</style>